{extend name="admin/plugin/layout" /}

{block name="content"}
<div class="container-fluid">
    <!-- 操作栏 -->
    <div class="row mb-3">
        <div class="col-md-6">
            <!-- 状态筛选 -->
            <div class="btn-group" role="group" aria-label="状态筛选">
                <input type="radio" class="btn-check" name="statusFilter" id="statusAll" value="all" checked>
                <label class="btn btn-outline-primary" for="statusAll">全部</label>

                <input type="radio" class="btn-check" name="statusFilter" id="statusEnabled" value="enabled">
                <label class="btn btn-outline-success" for="statusEnabled">已启用</label>

                <input type="radio" class="btn-check" name="statusFilter" id="statusDisabled" value="disabled">
                <label class="btn btn-outline-secondary" for="statusDisabled">未启用</label>
            </div>
        </div>
        <div class="col-md-6">
            <!-- 搜索框 -->
            <div class="input-group">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索..."
                    onkeypress="handleSearchKeypress(event)">
                <button class="input-group-text btn btn-primary" type="button" onclick="searchPlugins()">
                    <i class="fas fa-search"></i>
                </button>
                <button class="btn btn-primary ms-2" type="button" onclick="clearSearch()">
                    <i class="fas fa-times"></i>
                </button>
                <button class="btn btn-primary ms-1" type="button" onclick="refreshPlugins()" title="刷新列表">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- 插件列表容器 -->
    <div class="table-responsive">
        <div id="pluginList">
            <div class="d-flex justify-content-center align-items-center" style="height: 200px;">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">正在加载插件列表...</span>
                </div>
                <span class="ms-2">正在加载插件列表...</span>
            </div>
        </div>
    </div>
</div>

<!-- 插件配置弹出层 -->
<div class="modal fade" id="configModal" tabindex="-1" aria-labelledby="configModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="configModalTitle">插件配置</h5>
                <button type="button" class="btn-close" onclick="closeConfigModal()" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="configContent">
                    <div class="d-flex justify-content-center align-items-center" style="height: 100px;">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">正在加载配置...</span>
                        </div>
                        <span class="ms-2">正在加载配置...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="saveConfigBtn" onclick="savePluginConfig()">
                    <i class="fas fa-save"></i> 保存配置
                </button>
                <button type="button" class="btn btn-secondary" onclick="closeConfigModal()">取消</button>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="script"}
<script>
    // 刷新插件列表
    function refreshPlugins() {
        if (window.pluginManager) {
            const searchKeyword = document.getElementById('searchInput').value.trim();
            const statusFilter = document.querySelector('input[name="statusFilter"]:checked').value;
            window.pluginManager.loadPlugins(1, searchKeyword, statusFilter);
        }
    }

    // 搜索插件
    function searchPlugins() {
        const keyword = document.getElementById('searchInput').value.trim();
        const statusFilter = document.querySelector('input[name="statusFilter"]:checked').value;
        if (window.pluginManager) {
            window.pluginManager.loadPlugins(1, keyword, statusFilter);
        }
    }

    // 清空搜索
    function clearSearch() {
        document.getElementById('searchInput').value = '';
        const statusFilter = document.querySelector('input[name="statusFilter"]:checked').value;
        if (window.pluginManager) {
            window.pluginManager.loadPlugins(1, '', statusFilter);
        }
    }

    // 处理搜索框回车事件
    function handleSearchKeypress(event) {
        if (event.key === 'Enter') {
            searchPlugins();
        }
    }

    // 显示插件配置弹出层
    function showConfigModal(pluginName) {
        const modal = new bootstrap.Modal(document.getElementById('configModal'));
        const title = document.getElementById('configModalTitle');
        const content = document.getElementById('configContent');

        title.textContent = `插件配置 - ${pluginName}`;
        content.innerHTML = `
        <div class="d-flex justify-content-center align-items-center" style="height: 100px;">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">正在加载插件配置...</span>
            </div>
            <span class="ms-2">正在加载插件配置...</span>
        </div>
    `;
        modal.show();

        // 加载配置内容
        loadPluginConfig(pluginName);
    }

    // 关闭配置弹出层
    function closeConfigModal() {
        const modal = bootstrap.Modal.getInstance(document.getElementById('configModal'));
        if (modal) {
            modal.hide();
        }
    }

    // 加载插件配置
    async function loadPluginConfig(pluginName) {
        try {
            const response = await fetch(`/adminapi/plugin/view/getConfigHtml?plugin_name=${pluginName}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${window.pluginManager.token}`
                }
            });

            if (!response.ok) {
                throw new Error('网络请求失败');
            }

            const htmlContent = await response.text();
            document.getElementById('configContent').innerHTML = htmlContent;

        } catch (error) {
            document.getElementById('configContent').innerHTML =
                `<div class="error-message">加载插件配置失败: ${error.message}</div>`;
        }
    }

    // 保存插件配置
    async function savePluginConfig() {
        const form = document.getElementById('configForm');
        if (!form) return;

        const pluginName = form.dataset.plugin;
        const formData = new FormData(form);
        formData.append('plugin_name', pluginName);

        try {
            const manager = window.pluginManager;
            await manager.request(`${manager.baseUrl}/saveConfig`, {
                method: 'POST',
                body: formData
            });

            layer.msg('配置保存成功', { icon: 1, time: 1500 });
            closeConfigModal();

            // 不需要刷新列表，配置保存不影响插件状态显示
        } catch (error) {
            layer.msg('配置保存失败: ' + error.message, { icon: 2, time: 3000 });
        }
    }

    // 状态筛选事件监听
    document.addEventListener('DOMContentLoaded', function () {
        // 监听状态筛选变化
        document.querySelectorAll('input[name="statusFilter"]').forEach(radio => {
            radio.addEventListener('change', function () {
                const keyword = document.getElementById('searchInput').value.trim();
                const statusFilter = this.value;
                if (window.pluginManager) {
                    window.pluginManager.loadPlugins(1, keyword, statusFilter);
                }
            });
        });
    });

    // PluginManager已在script.js中初始化
</script>
{/block}